package com.lalameow.researchstation.kube

import com.lalameow.researchstation.ResearchStation
import com.lalameow.researchstation.api.technology.TechnologyCategories
import com.lalameow.researchstation.api.technology.TechnologyCriterion
import com.lalameow.researchstation.api.technology.TechnologyRegistries
import com.lalameow.researchstation.api.technology.TechnologyRequirement
import com.lalameow.researchstation.api.technology.TechnologyResource
import com.lalameow.researchstation.api.technology.TechnologyReward
import com.lalameow.researchstation.identifier
import dev.latvian.mods.kubejs.event.EventJS
import dev.latvian.mods.kubejs.script.ScriptType
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents

internal object ResearchingInitEventJS : EventJS() {
    fun technology(id: String) = TechnologyBuilderJS(id)

    fun category(id: String) = TechnologyCategoryBuilderJS(id)

    /**
     * 资源构建
     * @param id
     * @return
     */
    fun resource(id: String): Builder<out TechnologyResource<*>> =
        TechnologyRegistries.TECHNOLOGY_RESOURCE[ResearchStation.identifier(id)]?.invoke()
            ?: throw NoSuchElementException(id)

    /**
     * 奖励构建
     * @param id
     * @return
     */
    fun reward(id: String): Builder<out TechnologyReward> =
        TechnologyRegistries.TECHNOLOGY_REWARD[ResearchStation.identifier(id)]?.invoke()
            ?: throw NoSuchElementException(
                id
            )

    /**
     * 前置条件
     * @param id
     * @return
     */
    fun criterion(id: String): Builder<out TechnologyCriterion> =
        TechnologyRegistries.TECHNOLOGY_CRITERION[ResearchStation.identifier(id)]?.invoke()
            ?: throw NoSuchElementException(id)

    /**
     * 前置条件
     * @param id
     * @return
     */
    fun requirement(id: String): Builder<out TechnologyRequirement<*>> =
        TechnologyRegistries.TECHNOLOGY_REQUIREMENT[ResearchStation.identifier(id)]?.invoke()
            ?: throw NoSuchElementException(id)
}

internal fun ResearchStation.registerResearchingInitJS() {
    ServerLifecycleEvents.SERVER_STARTED.register {
        ResearchingInitEventJS.post(ScriptType.SERVER, "researching.init")
    }

    ServerLifecycleEvents.END_DATA_PACK_RELOAD.register { _, _, _ ->
        TechnologyCategories.clear()
        ResearchingInitEventJS.post(ScriptType.SERVER, "researching.init")
    }
}
